package 力扣日常刷题.木22二月.第14天220;

/**
 * @author 帅小伙
 * @date 2022/2/20
 * @description
 */
public class Demo124顺时针打印矩阵 {

    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int n = matrix.length, m = matrix[0].length;
        int[] ans = new int[n * m];
        int[] dx = new int[]{0, 1, 0, -1};
        int[] dy = new int[]{1, 0, -1, 0};
        boolean[][] isVisited = new boolean[n][m];
        int x = 0, y = 0,d = 0;
        for (int i = 0; i < n * m; i++) {
            ans[i] = matrix[x][y];
            isVisited[x][y] = true;
            x += dx[d%4];
            y += dy[d%4];
            if(x < 0 || x >= n || y < 0 || y >= m || isVisited[x][y]) {
                x -= dx[d%4];
                y -= dy[d%4];
                d++;
                x += dx[d%4];
                y += dy[d%4];
            }
        }
        return ans;
    }

}
